import { Button, Space } from 'antd';
import { Field } from 'sula';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
// import { useState, useEffect } from 'react';
// import type { ButtonProps } from 'antd';

const DynamicDepFieldComp = (props) => {
  const { list, disabled, className, style } = props;
  const [fields, { add, remove }] = list;
  return (
    <>
      <div className={className} style={{ ...style }}>
        {fields.map((field: any) => {
          const { name, key, fieldKey, ...rest } = field;
          return (
            <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
              {props.fields.map((fieldConfig: any) => {
                const { dependency = {} } = fieldConfig;
                const transedDep = Object.keys(dependency).reduce((memo, depType) => {
                  const dep = dependency[depType];
                  const relates = dep.relates.map((r: any) => {
                    return [fieldKey, ...(Array.isArray(r) ? r : [r])];
                  });
                  // eslint-disable-next-line no-param-reassign
                  memo[depType] = {
                    ...dep,
                    relates,
                  };
                  return memo;
                }, {});
                return (
                  <Field
                    {...rest}
                    key={key}
                    className={fieldConfig.className}
                    name={[name, fieldConfig.name]}
                    style={{ ...fieldConfig.style }}
                    fieldKey={[fieldKey, fieldConfig.name]}
                    rules={fieldConfig.rules}
                    field={fieldConfig.field}
                    remoteSource={fieldConfig.remoteSource}
                    initialSource={fieldConfig.initialSource}
                    // initialValue={fieldConfig.initialValue}
                    dependency={transedDep}
                  />
                );
              })}
              {!disabled && <MinusCircleOutlined onClick={() => remove(field.name)} key="remove" />}
            </Space>
          );
        })}
        {!disabled && (
          <Button
            style={{ width: 300 }}
            type="dashed"
            onClick={() => add()}
            block
            icon={<PlusOutlined />}
          >
            添加
          </Button>
        )}
      </div>
    </>
  );
};
export default DynamicDepFieldComp;
